package com.rayo.accesscontrollercopy.module.main;

import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.github.johnkil.print.PrintView;
import com.github.ybq.android.spinkit.SpinKitView;
import com.litesuits.common.utils.HexUtil;
import com.rayo.accesscontrollercopy.R;
import com.rayo.accesscontrollercopy.app.BaseFragment;
import com.rayo.accesscontrollercopy.config.Constants;
import com.rayo.accesscontrollercopy.config.GlobalVariables;
import com.rayo.accesscontrollercopy.model.db.bean.CalendarData;
import com.rayo.accesscontrollercopy.model.db.bean.CurrentUserData;
import com.rayo.accesscontrollercopy.model.db.bean.KeyData;
import com.rayo.accesscontrollercopy.model.db.bean.KeyTimezoneData;
import com.rayo.accesscontrollercopy.model.db.bean.KeyUserData;
import com.rayo.accesscontrollercopy.model.db.bean.PlanKeyAdd;
import com.rayo.accesscontrollercopy.model.db.bean.PlanKeyAddData;
import com.rayo.accesscontrollercopy.model.db.bean.SiteData;
import com.rayo.accesscontrollercopy.model.db.dao.CalendarDao;
import com.rayo.accesscontrollercopy.model.db.dao.CalendarImpl;
import com.rayo.accesscontrollercopy.model.db.dao.CurrentUserDao;
import com.rayo.accesscontrollercopy.model.db.dao.CurrentUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyDataDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyDataImp;
import com.rayo.accesscontrollercopy.model.db.dao.KeyTimeDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyTimeImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyUserDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.PlanKeyAddDao;
import com.rayo.accesscontrollercopy.model.db.dao.PlanKeyAddImpl;
import com.rayo.accesscontrollercopy.model.db.dao.SiteDao;
import com.rayo.accesscontrollercopy.model.db.dao.SiteImpl;
import com.rayo.accesscontrollercopy.model.network.WebSocketHelp;
import com.rayo.accesscontrollercopy.model.service.NetWorkService;
import com.rayo.accesscontrollercopy.module.adapter.MainFragmentAdapter;
import com.rayo.accesscontrollercopy.module.adapter.OnClicker;
import com.rayo.accesscontrollercopy.utils.BroadcastUtils;
import com.rayo.accesscontrollercopy.utils.CancelUtils;
import com.rayo.accesscontrollercopy.utils.TimeFormatUtil;
import com.rayo.accesscontrollercopy.utils.ToastUtils;
import com.rayo.keyholder.data.KeyHolderCmd;
import com.rayo.keyholder.data.KeyHolderData;
import com.rayo.keyholder.serialport.KeyHolderService;
import com.rayo.wallreader.data.KeyBasicInfo;
import com.rayo.wallreader.data.KeyType;
import com.rayo.wallreader.data.UserKeyInfo;
import com.rayo.wallreader.jni.WallreaderJni;
import com.rayo.wallreader.serialport.OnPortListener;
import com.rayo.wallreader.serialport.PortClass;
import com.rayo.wallreader.serialport.ReaderPort;
import com.rayo.wallreader.serialport.ReaderPortThread;
import com.rayo.wallreader.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.litesuits.common.utils.HandlerUtil.runOnUiThread;
import static com.rayo.accesscontrollercopy.config.Constants.BACKLOCK;
import static com.rayo.accesscontrollercopy.config.Constants.BACKLOCKTIME;
import static com.rayo.accesscontrollercopy.config.Constants.CHECKCONTROLLER;
import static com.rayo.accesscontrollercopy.config.Constants.CHECKDOOR;
import static com.rayo.accesscontrollercopy.config.Constants.CLOSE;
import static com.rayo.accesscontrollercopy.config.Constants.CLOSECONTROLLER;
import static com.rayo.accesscontrollercopy.config.Constants.OPENCONTROLLER;
import static com.rayo.accesscontrollercopy.config.Constants.OPENDOOR;
import static com.rayo.accesscontrollercopy.module.main.MainActivity.mKeyHolderService;


/**
 * Created by lyc-pc on 17/4/20.
 */

public class OpenFragment extends BaseFragment {

    private RecyclerView mRlvFragmentKey;

    //退出时的时间
    private long mExitTime;
    private Button mBtnActivityOpenGetkey;

    private TextView mBtnActivityOpenHint;
//    private RecyclerView mRlvActivityOpen;

    private Button mTvActivityOpenWrite;

    private SpinKitView mSvActivityOpenLoading;

    private PrintView mPvActivityOpenTime;

    private boolean mResult;
    private Thread mThread;

    private Thread thread;
    private Subscription mSubscription;
    private ReaderPortThread mReaderPortThread;
    private String keyId;
    private String reqId;
    private int errorCount = 0;
    private ObjectAnimator objectAnimator;
    private boolean posError = false;
    private boolean exist = true;
    //判断openfragment是否实例化完成,防止activity中的轮询影响
    private boolean start = false;
    private String serialNumber = "";

    private List<KeyData> list = new ArrayList<>(4);

    private KeyDataDao mKeyDataDao = new KeyDataImp();
    private KeyUserDao mKeyUserDao = new KeyUserImpl();
    private CurrentUserDao mCurrentUserDao = new CurrentUserImpl();
    private KeyUserData keyUserData;

    private KeyBasicInfo mKeyBasicInfo;
    private UserKeyInfo mUserKeyInfo;
    private int Action;
    private MainFragmentAdapter mAdapter;
    private List<KeyData> keyDataList;
    KeyDataDao keyDataDao = new KeyDataImp();
    private KeyData mKeyData;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 10:
                    Toast.makeText(getActivity(), R.string.noper, Toast.LENGTH_SHORT).show();
                    break;
                case Constants.BACKLOCK:
                    Action = Constants.BACKLOCK;
                    byte[] keyBack = {0, 0, 0, 0};
                    mKeyHolderService.sendData(new KeyHolderData((byte) mKeyData.getType(), (byte) mKeyData.getAddress(), (byte) 0x02, keyBack));
                    break;
                case 0:
                    byte[] key = {};
                    mKeyHolderService.sendData(new KeyHolderData((byte) mKeyData.getType(), (byte) mKeyData.getAddress(), (byte) 0x01, key));
                    handler.sendEmptyMessageDelayed(0, 100);
                    break;
                case 1:
                    byte[] key1 = {};
                    mKeyHolderService.sendData(new KeyHolderData((byte) 1, (byte) mKeyData.getKeybox(), (byte) 0x01, key1));
                    handler.sendEmptyMessageDelayed(1, 100);
                    break;
                case 3:
//                    getView().getKeySussess();
                    break;
                case 4:
//                    getView().returnKeySuccess();
                    break;
            }
        }
    };
    private BroadcastReceiver mKeyHolderReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuilder stringBuilder = new StringBuilder(64);
            final String action = intent.getAction();
            if (intent.getSerializableExtra(KeyHolderService.EXTRA_DATA) instanceof Integer) {
                return;
            }
            final KeyHolderData keyHolderData = (KeyHolderData) intent.getSerializableExtra(KeyHolderService.EXTRA_DATA);

            switch (action) {

                case KeyHolderService.ACTION_DATA_WRITE:
                    stringBuilder.append("MainSend:");
                    stringBuilder.append(com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()));
                    Log.e("write", stringBuilder.toString());
                    break;
                case KeyHolderService.ACTION_DATA_READ:
                    Log.e("cmd", keyHolderData.getCmd() + "");
                    stringBuilder.append("MainRead:");
                    stringBuilder.append(String.format("%02X", keyHolderData.getCmd()) + "-");
                    stringBuilder.append(String.format("%02X", keyHolderData.getDeviceType()) + "-");
                    stringBuilder.append(String.format("%02X", keyHolderData.getAddress()) + "-");
                    stringBuilder.append(com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()));

                    Log.e("read", stringBuilder.toString());
                    if (keyHolderData.getCmd() == -1) {

                        if (com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).equals("01")) {


                        }

                    } else if (keyHolderData.getCmd() == 2) {
                        if (com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).equals("01")) {
                            switch (Action) {
                                case BACKLOCK:
//                                    getView().finishActivity();
                                    break;
                                case CHECKDOOR:

                                    break;
                                case OPENDOOR:
                                    Action = OPENCONTROLLER;
                                    byte[] key = {1, 0, 0, 1};
                                    mKeyHolderService.sendData(new KeyHolderData((byte)mKeyData.getType(),(byte)mKeyData.getAddress(),(byte) 0x02,key));
                                    break;
                                case OPENCONTROLLER:
//                                    if (type==GET){
//                                        getView().showMessage(getContext().getString(R.string.devices_out));
//                                    }else  if (type==RETURN){
//                                        getView().showMessage(getContext().getString(R.string.devices_insert));
//                                    }
                                    mBtnActivityOpenHint.setText("门已开启，请取出钥匙");
                                    handler.sendEmptyMessageDelayed(BACKLOCK,BACKLOCKTIME);
                                    Action = CHECKCONTROLLER;
                                    handler.sendEmptyMessage(0);
                                    break;
                                case CLOSECONTROLLER:
                                    Action = CHECKDOOR;
                                    handler.removeMessages(BACKLOCK);
                                    handler.sendEmptyMessage(1);
//                                    getModule().upDataControllerBean(mKeyData);
//                                    getContext().sendBroadcast(new Intent().setAction(MainActivity.ACTION));
                                    break;
                                case CLOSE:
//                                    getView().close();
                                    break;


                            }
                        }else {

                        }
                    } else if (keyHolderData.getCmd() == 1) {

                        if ((com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).startsWith("01", 0))) {

                            switch (Action) {
                                case CHECKDOOR:
                                    if (com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).substring(22, 24).equals("01")) {//01开
//                                        Action = OPENCONTROLLER;
//                                        byte[] key = {1, 0, 0, 1};
//                                        mKeyHolderService.sendData(new KeyHolderData((byte) mKeyData.getType(), (byte) mKeyData.getAddress(), (byte) 0x02, key));
                                    } else {
                                        mBtnActivityOpenHint.setText("柜门已关闭，请对钥匙进行授权");
                                        handler.removeMessages(1);
                                        doListen();
//                                        Action = OPENDOOR;
//                                        byte[] key = {1, 0, 0, 0};
//                                        mKeyHolderService.sendData(new KeyHolderData((byte) DOORTYPE, (byte) mKeyData.getBoxid(), (byte) 0x02, key));
                                    }
                                    break;
                                case CHECKCONTROLLER:
                                    if (HexUtil.encodeHexStr(keyHolderData.getData()).substring(14, 22).equals("00000000")&&
                                            com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).substring(22, 24).equals("00" )) {
                                        mBtnActivityOpenHint.setText("钥匙已取出，请关闭柜门");
                                        mKeyData.setUse(true);
                                        keyDataDao.updateKeyData(mKeyData);
                                        Action = CLOSECONTROLLER;
                                        handler.removeMessages(0);
                                        byte[] key = {0, 0, 0, 0};
                                        mKeyHolderService.sendData(new KeyHolderData((byte) mKeyData.getType(), (byte) mKeyData.getAddress(), (byte) 0x02, key));
                                    }
                                    break;
                            }

                            if (!com.rayo.wallreader.utils.HexUtil.encodeHexStr(keyHolderData.getData()).substring(14, 22).equals("00000000")) {

                            }
                        }
                    }
                    break;
                case KeyHolderService.ACTION_CLOSE:
                    break;
                default:
                    break;
            }
        }
    };
    private IntentFilter makeUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(KeyHolderService.ACTION_DATA_READ);
        intentFilter.addAction(KeyHolderService.ACTION_DATA_WRITE);
        intentFilter.addAction(KeyHolderService.ACTION_CLOSE);
        intentFilter.addAction(MainActivity.STATUS);
        return intentFilter;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_open;
    }

    @Override
    protected void setupViews() {
        mBtnActivityOpenGetkey = (Button) rootView.findViewById(R.id.btn_activity_open_getkey);
        mBtnActivityOpenHint = (TextView) rootView.findViewById(R.id.hint_tv);
//        mRlvActivityOpen = (RecyclerView) rootView.findViewById(R.id.rlv_activity_open);
        mTvActivityOpenWrite = (Button) rootView.findViewById(R.id.tv_activity_open_write);
        mSvActivityOpenLoading = (SpinKitView) rootView.findViewById(R.id.sv_activity_open_loading);
        mPvActivityOpenTime = (PrintView) rootView.findViewById(R.id.pv_activity_open_time);
        mRlvFragmentKey = rootView.findViewById(R.id.recycleview);
    }

    @Override
    protected void initialized() {
        initData();
    }

    private void initData() {
        MainActivity.KEY = 1;

//        mSvActivityOpenLoading.setIndeterminateDrawable(new Wave());
        Bundle bundle = getArguments();
        keyId = bundle.getString("keyid");
        Log.e("keyid", keyId + "");
        keyDataList = keyDataDao.getAll();
        mAdapter = new MainFragmentAdapter(keyDataList, getContext());
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(getContext(), 8);
        mRlvFragmentKey.setLayoutManager(mGridLayoutManager);
        mRlvFragmentKey.setAdapter(mAdapter);
        mAdapter.setOnClicker(new OnClicker() {
            @Override
            public void click(View v, int pos) {
                mKeyData =  keyDataList.get(pos);
                Action = OPENDOOR;
                byte[] key = {1, 0, 0, 0};
                mKeyHolderService.sendData(new KeyHolderData((byte) 1, (byte) 2, (byte) 0x02, key));
            }

            @Override
            public void onClick(View v, int pos, KeyData keyData) {

            }

            @Override
            public void longClick(View v, int pos) {

            }
        });
        getActivity().registerReceiver(mKeyHolderReceiver, makeUpdateIntentFilter());
        mBtnActivityOpenGetkey.setOnClickListener(this);
        mTvActivityOpenWrite.setOnClickListener(this);

        exist = true;
        mHardware.DoorState(0);
//        mPvActivityOpenTime.setVisibility(View.VISIBLE);
        mBtnActivityOpenGetkey.setClickable(false);
        BroadcastUtils.send(getContext(), MainActivity.STOP);
    }

    private void initReg() {

    }

    private void doListen() {
        stop();
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                mKeyBasicInfo = new KeyBasicInfo();
                NetWorkService.STATES =false;
                List<PortClass> port = new ArrayList<>();
                PortClass portClass = new PortClass(ReaderPort.DETIVER_2,true,true,false);
                port.add(portClass);
                stop();
                mReaderPortThread = new ReaderPortThread(port) {

                    @Override
                    protected void onSendNfcKeyReader(String s, int i) {
                            mKeyBasicInfo.setKeyType(KeyBasicInfo.NFC_KEY);
                            byte[] code = new byte[16];
                            byte[] sys_Code = HexUtil.decodeHex(GlobalVariables.getInstance().getmSiteData().getSyscode().toCharArray());
                            if (null != sys_Code && 8 == sys_Code.length) {
                                int ret = WallreaderJni.getmInstance().des(1, sys_Code, sys_Code.length, code);
                                if (ret > 0) {

                                    System.arraycopy(code, 0, mKeyBasicInfo.getSysCode(), 0, 4);
//                        System.arraycopy(code, 0, keyBasicInfo.getSysCode(), 0, 4);
//                        System.arraycopy(code, 0,  this.cardBasicInfo.getSysCode(), 0, 4);
                                }
                            }
                            byte[] reg_Code = HexUtil.decodeHex(GlobalVariables.getInstance().getmSiteData().getRegcode().toCharArray());
                            if (null != reg_Code && 8 == reg_Code.length) {
                                int ret = WallreaderJni.getmInstance().des(1, reg_Code, reg_Code.length, code);
                                if (ret > 0) {
                                    System.arraycopy(code, 0, mKeyBasicInfo.getRegCode(), 0, 4);
//                        System.arraycopy(code, 0, keyBasicInfo.getRegCode(), 0, 4);
//                        System.arraycopy(code, 0, this.cardBasicInfo.getRegCode(), 0, 4);
                                }
                            }
                            writeToKey(mReaderPortThread, mKeyBasicInfo);
                            this.stop();
                            if (!mResult) {


                                if (posError) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getContext(), getString(R.string.Getting_key_from_wrong_position), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } else if (!exist) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getContext(), getString(R.string.This_key_is_not_registered), Toast.LENGTH_SHORT).show();
                                            doListen();
                                        }
                                    });

                                } else if (!posError && exist) {
                                    errorCount++;
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (errorCount == 3) {
                                                mTvActivityOpenWrite.setVisibility(View.VISIBLE);
                                                Toast.makeText(getContext(), R.string.failed, Toast.LENGTH_SHORT).show();
                                            } else if (errorCount < 3) {
                                                doListen();
                                            }

                                        }
                                    });
                                }
                            } else {
                                WebSocketHelp.getmInstance().updateUserFinish(Integer.parseInt(keyId),2);
                                KeyData keyData = mKeyDataDao.getKeyDataBySerialnumber(serialNumber);
                                if (keyData != null) {
                                    keyData.setUsecount(keyData.getUsecount() + 1);
                                    mKeyDataDao.updateKeyData(keyData);
                                }
                                CurrentUserData currentUserData = new CurrentUserData();
                                currentUserData.setUserid(keyId);
                                currentUserData.setKeysn(serialNumber);
                                currentUserData.setFname(keyUserData.getFname());
                                currentUserData.setLname(keyUserData.getLname());
                                currentUserData.setTagid(keyData.getTagid());
                                currentUserData.setTime(new Date());
                                mCurrentUserDao.add(currentUserData);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getContext(), R.string.auth_successful, Toast.LENGTH_SHORT).show();
                                        MainActivity.KEY=0;
                                        byte[] key = TimeFormatUtil.inttoTwoBytes(1000);
//                                        mKeyHolderService.sendData(new KeyHolderData(address,(byte) 0x0c, key));
                                        getActivity().onBackPressed();

                                    }
                                });
                            }
                    }

                    @Override
                    protected void onSendBleKeyReader(String s, int i) {
                        SiteDao siteDao = new SiteImpl();
                        SiteData siteData = siteDao.findFirst();
                        if (siteData==null){
                            handler.sendEmptyMessage(10);
                            return;
                        }
                        if (!siteData.getSupportkey().contains("BLE")){
                            handler.sendEmptyMessage(10);
                            return;
                        }

                            mKeyBasicInfo.setKeyType(KeyBasicInfo.BLE_KEY);
                            byte[] code = new byte[16];
                            byte[] sys_Code = HexUtil.decodeHex(GlobalVariables.getInstance().getmSiteData().getSyscode().toCharArray());
                            if (null != sys_Code && 8 == sys_Code.length) {
                                int ret = WallreaderJni.getmInstance().des(1, sys_Code, sys_Code.length, code);
                                if (ret > 0) {

                                    System.arraycopy(code, 0, mKeyBasicInfo.getSysCode(), 0, 4);
//                        System.arraycopy(code, 0, keyBasicInfo.getSysCode(), 0, 4);
//                        System.arraycopy(code, 0,  this.cardBasicInfo.getSysCode(), 0, 4);
                                }
                            }
                            byte[] reg_Code = HexUtil.decodeHex(GlobalVariables.getInstance().getmSiteData().getRegcode().toCharArray());
                            if (null != reg_Code && 8 == reg_Code.length) {
                                int ret = WallreaderJni.getmInstance().des(1, reg_Code, reg_Code.length, code);
                                if (ret > 0) {
                                    System.arraycopy(code, 0, mKeyBasicInfo.getRegCode(), 0, 4);
//                        System.arraycopy(code, 0, keyBasicInfo.getRegCode(), 0, 4);
//                        System.arraycopy(code, 0, this.cardBasicInfo.getRegCode(), 0, 4);
                                }
                            }
                            writeToKey(mReaderPortThread, mKeyBasicInfo);
                            this.stop();
                            if (!mResult) {


                                if (posError) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getContext(), getString(R.string.Getting_key_from_wrong_position), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } else if (!exist) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getContext(), getString(R.string.This_key_is_not_registered), Toast.LENGTH_SHORT).show();
                                            doListen();
                                        }
                                    });

                                } else if (!posError && exist) {
                                    errorCount++;
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (errorCount == 3) {
                                                mTvActivityOpenWrite.setVisibility(View.VISIBLE);
                                                Toast.makeText(getContext(), R.string.failed, Toast.LENGTH_SHORT).show();
                                            } else if (errorCount < 3) {
                                                doListen();
                                            }

                                        }
                                    });
                                }
                            } else {
                                KeyData keyData = mKeyDataDao.getKeyDataBySerialnumber(serialNumber);
                                if (keyData != null) {
                                    keyData.setUsecount(keyData.getUsecount() + 1);
                                    mKeyDataDao.updateKeyData(keyData);
                                }
                                CurrentUserData currentUserData = new CurrentUserData();
                                currentUserData.setUserid(keyId);
                                currentUserData.setKeysn(serialNumber);
                                currentUserData.setFname(keyUserData.getFname());
                                currentUserData.setLname(keyUserData.getLname());
                                currentUserData.setTagid(keyData.getTagid());
                                currentUserData.setTime(new Date());
                                mCurrentUserDao.add(currentUserData);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getContext(), R.string.auth_successful, Toast.LENGTH_SHORT).show();
                                        MainActivity.KEY=0;
//                                        byte[] key = TimeFormatUtil.inttoTwoBytes(1000);
//                                        mKeyHolderService.sendData(new KeyHolderData(address,(byte) 0x0c, key));
                                        getActivity().onBackPressed();
                                    }
                                });
                            }
                    }

                    @Override
                    protected void onSendCardReader(String s, int i, byte[] bytes) {

                    }

                    @Override
                    protected void onNoReader(String s, int i) {

                    }

                    @Override
                    protected void onPlugInRelay(String s, int i) {

                    }

                    @Override
                    protected void onStopReader() {

                    }


                };
                mThread = new Thread(mReaderPortThread);
                mThread.start();
            }
        });
        thread.start();
    }

    private void startAni() {
        if (objectAnimator == null) {
            objectAnimator = ObjectAnimator.ofFloat(mPvActivityOpenTime, "alpha", 1f, 0f);
            objectAnimator.setDuration(1000);
        }
        objectAnimator.start();
    }

    private void clearAni() {
        if (objectAnimator != null && objectAnimator.isRunning()) {
            objectAnimator.cancel();
        }
    }

    private IHardware mHardware;

    public void setHardware(IHardware h) {
        this.mHardware = h;
    }


//
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (mSvActivityOpenLoading.getVisibility() == View.GONE) {
//
//            } else if (mSvActivityOpenLoading.getVisibility() == View.VISIBLE) {
//
//                mSvActivityOpenLoading.setVisibility(View.GONE);
//                return true;
//            }
//        }
//        return super.onKeyDown(keyCode, event);
//    }


    // 返回键按下时会被调用
    public void onKeyDown() {
        if ((System.currentTimeMillis() - mExitTime) > 1000) {
            Toast.makeText(getActivity(), getString(R.string.onkey_hint), Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            MainActivity.KEY=0;
            getActivity().onBackPressed();

        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        start = false;
        mHardware = null;
        mThread = null;
        thread = null;
        clearAni();
        NetWorkService.STATES =true;
        stop();
        getActivity().unregisterReceiver(mKeyHolderReceiver);
        handler.removeCallbacksAndMessages(null);
        CancelUtils.unsubscribe(mSubscription);
    }

    private void stop() {
        if (mReaderPortThread != null && !mReaderPortThread.isStop) {
            mReaderPortThread.stop();
        }
    }

    private void pause() {
        if (null != mReaderPortThread)
            mReaderPortThread.onPause();
    }

    private void resume() {
        if (null != mReaderPortThread) {
            mReaderPortThread.onResume();
        }
    }

    private void writeToKey(final ReaderPortThread mReaderPortThread, KeyBasicInfo keyBasicInfo) {


        if (connectKey(mReaderPortThread, keyBasicInfo)) {

            SiteDao siteDao = new SiteImpl();
            SiteData siteData = siteDao.findFirst();
            if (siteData.getSupportkey()==null){
                handler.sendEmptyMessage(10);
                mResult=false;
                this.stop();
                return;
            }
            if (keyBasicInfo.getVersion().contains("RCLB")){
                if (!siteData.getSupportkey().substring(0,3).equals("NFC")){
                    handler.sendEmptyMessage(10);
                    mResult=false;
                    this.stop();
                    return;
                }
            }else if (keyBasicInfo.getVersion().contains("B03014")){
                if (!siteData.getSupportkey().contains("MiniNFC")){
                    handler.sendEmptyMessage(10);
                    mResult=false;
                    this.stop();
                    return;
                }
            }
            pause();
            mUserKeyInfo = new UserKeyInfo();
            writeUserKey(mKeyBasicInfo, mUserKeyInfo);
            resume();
            mReaderPortThread.getmPortReadBiz().writeUserKey(mKeyBasicInfo, mUserKeyInfo, new OnPortListener.OnWriteKeyListener() {
                @Override
                public void writeKeySuccess() {
                    mResult = true;
                    Log.e("write", "Write user key success");
                }


                @Override
                public void writeKeyFailed() {
                    Log.e("write", "Write user key failed");
                    mResult = false;
                }
            });
//            mKeyBasicInfo.setRegCode(HexUtil.decodeHex(AppUtils.getDecode(GlobalVariables.getInstance().getmSiteData().getRegcode()).toCharArray()));
//            mKeyBasicInfo.setSysCode(HexUtil.decodeHex(AppUtils.getDecode(GlobalVariables.getInstance().getmSiteData().getSyscode()).toCharArray()));
//            mReaderPortThread.getmPortReadBiz().registerKey(mKeyBasicInfo, new OnPortListener.OnWriteKeyListener() {
//                @Override
//                public void writeKeySuccess() {
//
//                }
//
//                @Override
//                public void writeKeyFailed() {
//
//                }
//            });

        }

    }

    private boolean connectKey(final ReaderPortThread mReaderPortThread, final KeyBasicInfo pKeyBasicInfo) {
        mReaderPortThread.getmPortReadBiz().findKey(pKeyBasicInfo, new OnPortListener.OnFindListener() {
            @Override
            public void findSuccess() {
                String txt = "Find key successfully \n";
                txt += "Key Id: " + pKeyBasicInfo.getKeyId() + "\n";
                txt += "Key Type: "
                        + String.format("%2X", pKeyBasicInfo.getType())
                        + "\n";
                txt += "Key Group Id: " + pKeyBasicInfo.getGroupId()
                        + "\n";
                txt += "Key Version: " + pKeyBasicInfo.getVersion()
                        + "\n";
                txt += "Key Serial Number: "
                        + HexUtil.encodeHexStr(pKeyBasicInfo
                        .getSerial()) + "\n";
                txt += "Key Time: "
                        + TimeFormatUtil.localDateTimeFormat(TimeUtils
                        .dateFromNotYMDWHMS(
                                HexUtil.encodeHexStr(pKeyBasicInfo
                                        .getKeyTime()))
                        .getTime()) + "\n";
                Log.e(getContext().getClass().getSimpleName() + "txt", txt);
                KeyData keyData = mKeyDataDao.getKeyDataBySerialnumber(HexUtil.encodeHexStr(pKeyBasicInfo
                        .getSerial()));
                serialNumber=HexUtil.encodeHexStr(pKeyBasicInfo
                        .getSerial());
                if (keyData == null) {
                    exist = false;
//                    posError = false;
                    mResult = false;
                    Log.e("sdsds", "jjjj");
                } else {
                    exist = true;
//                        posError = true;
                    mResult = true;
                    Log.e("sdsds", "jjjj2");

                }
            }

            @Override
            public void findFailed() {
                Log.e(getContext().getClass().getSimpleName() + "findkeyfailed", "findkeyfailed");
                exist = true;
                mResult = false;
//                byte reg[] = {49,49,49,49};
//                byte sys[] = {54,54,54,54};
//                mKeyBasicInfo.setRegCode(reg);
//                mKeyBasicInfo.setSysCode(sys);
//                writeToKey(mReaderPortThread, mKeyBasicInfo);
            }
        });
        return mResult;
    }

    private void writeUserKey(KeyBasicInfo mKeyBasicInfo, UserKeyInfo mUserKeyInfo
    ) {
        mKeyBasicInfo.setKeyId(Integer.parseInt(keyId));
        mKeyBasicInfo.setType(KeyType.USER_KEY.toInteger());
        mKeyBasicInfo.setKeyTime(TimeUtils.calToBytesYMDWHMS(Calendar
                .getInstance()));

        keyUserData = mKeyUserDao.findByUserid(keyId);
        Date keyIssueTime = TimeUtils.dateFromYMDHMS(
                HexUtil.encodeHexStr(mKeyBasicInfo.getKeyIssueTime()));
        if (keyUserData != null && keyUserData.getEditime().getTime() >= keyIssueTime.getTime()) {

            mKeyBasicInfo.setBeginTime(TimeUtils.dateToBytesYMDHM(keyUserData.getBegin()));
            mKeyBasicInfo.setEndTime(TimeUtils.dateToBytesYMDHM(keyUserData.getEnd()));
            mKeyBasicInfo.setVerifyDay(Integer.parseInt(keyUserData.getValday()));
        }
        Calendar nowtime = Calendar.getInstance();
        mKeyBasicInfo.setKeyIssueTime(TimeUtils.dateToBytesYMDHM(nowtime
                .getTime()));
        List<UserKeyInfo.TimezoneInfo> timeList = new ArrayList<UserKeyInfo.TimezoneInfo>();
        List<UserKeyInfo.ZoneInfo> zoneList = new ArrayList<UserKeyInfo.ZoneInfo>();
        KeyTimeDao keyTimeDao = new KeyTimeImpl();
        List<KeyTimezoneData> keyTimeList = keyTimeDao.findAll();
        for (int z = 0, size = keyTimeList.size() / 12; z < size; z++) {
            KeyTimezoneData keyTimezoneData = keyTimeDao.findByNo((z + 1), 1);
            if (keyTimezoneData != null) {
                for (int t = 0; t < 12; t++) {
                    KeyTimezoneData keyTimezoneData1 = keyTimeDao.findByNo((z + 1), (t + 1));
                    UserKeyInfo.TimezoneInfo time = new UserKeyInfo.TimezoneInfo();
//                    Date date = new Date(13, 5, 00, 00, 00);
                    time.ZoneNo = z + 1;
                    time.TimeNo = t + 1;
                    time.From.setTime(keyTimezoneData1.getFrom());
//                    date = new Date(18, 8, 19, 23, 59);
                    time.To.setTime(keyTimezoneData1.getTo());
                    if (keyTimezoneData1.getSun() == 1) {
                        time.Su = true;
                    } else {
                        time.Su = false;
                    }
                    if (keyTimezoneData1.getMon() == 1) {
                        time.Mo = true;
                    } else {
                        time.Mo = false;
                    }
                    if (keyTimezoneData1.getTue() == 1) {
                        time.Tu = true;
                    } else {
                        time.Tu = false;
                    }
                    if (keyTimezoneData1.getWed() == 1) {
                        time.We = true;
                    } else {
                        time.We = false;
                    }
                    if (keyTimezoneData1.getThu() == 1) {
                        time.Th = true;
                    } else {
                        time.Th = false;
                    }
                    if (keyTimezoneData1.getFri() == 1) {
                        time.Fr = true;
                    } else {
                        time.Fr = false;
                    }
                    if (keyTimezoneData1.getSat() == 1) {
                        time.Sa = true;
                    } else {
                        time.Sa = false;
                    }
                    if (keyTimezoneData1.getSp1() == 1) {
                        time.Sp1 = true;
                    } else {
                        time.Sp1 = false;
                    }
                    if (keyTimezoneData1.getSp2() == 1) {
                        time.Sp2 = true;
                    } else {
                        time.Sp2 = false;
                    }
                    if (keyTimezoneData1.getHol() == 1) {
                        time.Hol = true;
                    } else {
                        time.Hol = false;
                    }
                    timeList.add(time);
                }
                UserKeyInfo.ZoneInfo zone = new UserKeyInfo.ZoneInfo();
                zone.ZoneNo = z + 1;
                zone.TimeCount = 12;
                zoneList.add(zone);
            }
        }
        mUserKeyInfo.setTimezoneInfo(timeList);
        mUserKeyInfo.setZoneInfo(zoneList);
        mUserKeyInfo.setTimezoneCount(zoneList.size());
        CalendarDao calendarDao = new CalendarImpl();
        List<CalendarData> calendarDataList = calendarDao.findByCalId(keyUserData.getCalendar());
        if (null != calendarDataList) {
            List<UserKeyInfo.CalendarInfo> calendarInfoList = new ArrayList<>();
            for (CalendarData calendarData : calendarDataList) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(calendarData.getCalendar());
                calendarInfoList.add(new UserKeyInfo.CalendarInfo(calendar, calendarData.getType()));
            }
            mUserKeyInfo.setCalendarInfo(calendarInfoList);
        }


        List<UserKeyInfo.Open> openList = new ArrayList<>();
        //
//            PlanKeyDelDao keyDelDao = new PlanKeyDelImpl();
//            List<PlanKeyDelData> planKeyDelDataList = keyDelDao.findPlanKeyByUserId(Integer.parseInt(keyId));
//            if (null != planKeyDelDataList && planKeyDelDataList.size() > 0) {
//                StringBuilder sb = new StringBuilder(64);
//                for (PlanKeyDelData planKeyDelData : planKeyDelDataList) {
//                    sb.append(planKeyDelData.getData());
//                }
//                List<PlanKeyDel> keyDels = JSONArray.parseArray(sb.toString(), PlanKeyDel.class);
//                for (PlanKeyDel planKeyDel : keyDels) {
//                    openList.add(new UserKeyInfo.Open(Integer.valueOf(planKeyDel.getType()), Integer.valueOf(planKeyDel.getLockid()), 0));
//                }
//            }

        PlanKeyAddDao keyAddDao = new PlanKeyAddImpl();
        Log.e("keyid",keyId+"");
        List<PlanKeyAddData> planKeyAddList = keyAddDao.findPlanKeyByUserId(Integer.parseInt(keyId));
        if (null != planKeyAddList && planKeyAddList.size() > 0) {
            StringBuilder sb = new StringBuilder(64);
            for (PlanKeyAddData planKeyAddData : planKeyAddList) {
                sb.append(planKeyAddData.getData());
            }
            List<PlanKeyAdd> keyAdds = JSONArray.parseArray(sb.toString(), PlanKeyAdd.class);
            for (PlanKeyAdd planKeyAdd : keyAdds) {
                if (mKeyBasicInfo.getKeyType() != KeyBasicInfo.BLE_KEY) {
                    openList.add(new UserKeyInfo.Open(Integer.valueOf(planKeyAdd.getType()), Integer.valueOf(planKeyAdd.getLockid()), Integer.valueOf(planKeyAdd.getTimezoneid())));
                } else {
                    if(Integer.parseInt(planKeyAdd.getType())==2||Integer.parseInt(planKeyAdd.getType())==4) {
                        openList.add(new UserKeyInfo.Open(UserKeyInfo.Open.LOCK_TYPE, Integer.valueOf(planKeyAdd.getLockid()),
                                Integer.valueOf(planKeyAdd.getTimezoneid())));
                    }
                    else {
                        openList.add(new UserKeyInfo.Open(UserKeyInfo.Open.GROUP_TYPE, Integer.valueOf(planKeyAdd.getLockid()),
                                Integer.valueOf(planKeyAdd.getTimezoneid())));
                    }
                }

            }
            for(int i=0;i<openList.size();i++){
                Log.e("addplan",openList.get(i).Type+""+"  "+openList.get(i).OpenId+""+"  "+openList.get(i).TimeZoneId+"");
            }
        }
        mUserKeyInfo.setOpens(openList);
//        Log.e(getContext().getClass().getSimpleName() + "write",  mKeyBasicInfo.getKeyId() + ""
//                + "  " +HexUtil.encodeHexStr( mKeyBasicInfo.getSysCode()) + ""+"   "+HexUtil.encodeHexStr(mKeyBasicInfo.getRegCode()) + "  " + mKeyBasicInfo.getGroupId() + "");

    }

    private void swich(KeyData keyData1, KeyData keyData2) {
        KeyData temp = null;
        temp = keyData1;
        keyData1 = keyData2;
        keyData2 = temp;
        temp = null;
    }

    private byte[] getArray(int pos) {
        byte[] ret = new byte[4];
        if (pos == 1) {
            ret[0] = 0x01;
            ret[1] = 0x00;
            ret[2] = 0x00;
            ret[3] = 0x00;
        } else if (pos == 2) {
            ret[0] = 0x00;
            ret[1] = 0x01;
            ret[2] = 0x00;
            ret[3] = 0x00;
        } else if (pos == 3) {
            ret[0] = 0x00;
            ret[1] = 0x00;
            ret[2] = 0x01;
            ret[3] = 0x00;
        } else if (pos == 4) {
            ret[0] = 0x00;
            ret[1] = 0x00;
            ret[2] = 0x00;
            ret[3] = 0x01;
        }
        return ret;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_activity_open_getkey:
//                posError = false;
                exist = true;
                mHardware.DoorState(0);
                mPvActivityOpenTime.setVisibility(View.VISIBLE);
                mBtnActivityOpenGetkey.setClickable(false);
                BroadcastUtils.send(getContext(), MainActivity.STOP);
                mSubscription = Observable.create(new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
//                        CurrentUserData currentUserData = mCurrentUserDao.findByUserId(keyId);
//                        if (currentUserData == null) {
                            subscriber.onNext(getString(R.string.ic_three));
                            SystemClock.sleep(1000);
                            subscriber.onNext(getString(R.string.ic_two));
                            SystemClock.sleep(1000);
                            subscriber.onNext(getString(R.string.ic_one));
                            SystemClock.sleep(1000);
                            subscriber.onCompleted();
//                        }else {
//                            getActivity().runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    handler.postDelayed(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            BroadcastUtils.send(getContext(), MainActivity.START);
//                                        }
//                                    }, 5 * 100);
//                                    Toast.makeText(getContext(), getString(R.string.must_return_key), Toast.LENGTH_SHORT).show();
//                                    CancelUtils.unsubscribe(mSubscription);
//                                }
//                            });
//                        }
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                        start = true;
                        mBtnActivityOpenGetkey.setClickable(true);
                        mPvActivityOpenTime.setVisibility(View.GONE);
                        byte[] key = {};
//                        mKeyHolderService.sendData(new KeyHolderData(address,KeyHolderCmd.READ_KEY_LOCKED_COUNT, key));
                    }

                    @Override
                    public void onError(Throwable e) {
                        mBtnActivityOpenGetkey.setClickable(true);

                        Log.e(getContext().getClass().getSimpleName() + "openerror", e.toString());
                    }

                    @Override
                    public void onNext(String s) {
                        byte[] key = TimeFormatUtil.inttoTwoBytes(50);
//                        mKeyHolderService.sendData(new KeyHolderData(address,(byte) 0x0c, key));
                        mPvActivityOpenTime.setIconText(s);
                        startAni();
                    }
                });
                break;
            case R.id.tv_activity_open_write:
                errorCount = 0;
                mTvActivityOpenWrite.setVisibility(View.GONE);
                doListen();
                break;
        }
    }
}
